<template>
	<view class="wrap" style="padding-bottom: 60px;">
		<u-card class="task-list-item" :border="false" padding="20" margin="20rpx">
			<view class="" slot="body">
				<u-form :model="queryParam" ref="uForm" >
						<u-form-item label="订单" v-if="!(!queryParam.orderNumber && queryParam.orderId)"><u-input readonly v-model="queryParam.orderNumber" placeholder="请关联销售订单" @click="linkOrder"/></u-form-item>
						<u-form-item label="选择测量员" label-width="240rpx"><u-input placeholder="请选择" v-model="queryParam.measurerName" type="select" @click="show = true"/></u-form-item>
						<u-form-item label="地址"><u-input v-model="queryParam.address" placeholder="请输入地址"/></u-form-item>
						<u-form-item label-width="140" label="业主电话"><u-input v-model="queryParam.phone"placeholder="请输入业主电话" /></u-form-item>
						<u-form-item label="备注"><u-input type="textarea" v-model="queryParam.remark" placeholder="请输入备注" border></u-input></u-form-item>
				</u-form>
				<view class="apply-text"><span>配件信息：</span></view>
				<u-upload ref="upload_file" :fileList="fileList" @afterRead="afterRead"
					@on-choose-complete="onChooseComplete" @on-remove="removeSuccess" name="1" multiple :maxCount="9" :auto-upload="false"
					@on-success="uploadSuccess"
					:previewFullImage="true"></u-upload>
			</view>
		</u-card>
		<u-row gutter="32" class="bottom-box" justify="center">
			<u-col span="12">
				<view><u-button type="primary" shape="circle" @click="submit()">确定</u-button></view>
			</u-col>
		</u-row>
		
		<u-select v-model="show" :list="userList" valueName="id" labelName="name" @confirm="confirm"></u-select>
	</view>
</template>

<script>
	import moment from 'moment' 
	export default {
		data() {
			return {
				show: false,
				queryParam: {},
				list:[{},{}],
				fileList: [],
				text: null,
				current:1,
				saleOrderAttaches:[],
				userList:[],
			}
		},
		onLoad(options) {
			this.queryParam = options
			this.$set(this.queryParam,'measureStatus',+options.measureStatus)
		},
		
		onShow() {
			uni.$off('linkBillOk')
			uni.$on('linkBillOk',(res)=>{
				this.$set(this.queryParam,'orderNumber',res.orderNumber)
				this.queryParam.orderId = res.id
				if(!this.queryParam.id){
					// 新增就填电话等信息
					
					this.$set(this.queryParam,'phone',res.phone)
					this.$set(this.queryParam,'address',res.address)
					
				}
			})
			this.getAllUserList()
		},
		methods: {
				getDetail(){
					let param = {
						id:this.queryParam.id
					}
					this.$u.api.bizOrderAccessoryInfo(param).then(res=>{
						if(res.code === 200){
							this.queryParam = res.data
							let arr = this.queryParam.fileList ? this.queryParam.fileList.split(',') : []
							this.fileList = arr.map(img=>{
								let obj ={
									error: false,
									file: {
										path:img.replace(/\\/g,'/')
									},
									progress: 100,
									url: img.replace(/\\/g,'/')
								}
								return obj
							})
							this.saleOrderAttaches = arr.map(img=>{
								let obj ={
									orderId:this.queryParam.id,
									attachPath:img.replace(/\\/g,'/'),
								}
								return obj
							})
						}
					})
				},
				submit() {
					if(!this.queryParam.id){
					let that = this;
					let fileList = this.saleOrderAttaches.map(v=>v.attachPath)
					console.log(fileList,'fileList');
					console.log(this.saleOrderAttaches,'this.saleOrderAttaches');
					// return;
					uni.showModal({
						title: '提示',
						content: `确认提交？`,
						success: (res)=>{
							if (res.confirm) {
								let param ={
									fileList:fileList.join(','),
									remark:this.queryParam.remark,
									address:this.queryParam.address,
									phone:this.queryParam.phone,
									status:0,
									orderId:this.queryParam.orderId,
									measurer:this.queryParam.measurer,
									measurerName:this.vuex_user.name,
									measureStatus: +!!fileList.length, 
									measureDate:moment(new Date()).format('YYYY-MM-DD')
								}
								if(this.queryParam.id){
									param = this.queryParam
									param.fileList = fileList.join(',')
								}
								this.$u.api.addMeasure(param).then(res=>{
									if(res.code == 200){
										this.$u.toast('操作成功！') 
										setTimeout(()=>{
											let pages = getCurrentPages();
											let prevPage = pages[pages.length - 2]; //上一个页面
											prevPage.$vm.loadData({num:1,size:10})
											uni.navigateBack()
										},1500)
									}
								})
							}
						}
					});
					
					}else{
					let that = this;
					uni.showModal({
						title: '提示',
						content: `确认完成测量？`,
						success: (res)=>{
							if (res.confirm) {
								this.queryParam.fileList = this.saleOrderAttaches.map(v=>v.attachPath).join(',')
								this.queryParam.measureStatus = +!!this.saleOrderAttaches.length
								this.$u.api.updateBizMeasure(this.queryParam).then(res=>{
									if(res.code == 200){
										this.$u.toast('操作成功！')
										setTimeout(()=>{
											let pages = getCurrentPages();
											let prevPage = pages[pages.length - 2]; //上一个页面
											prevPage.$vm.change(+!!this.saleOrderAttaches.length)
											uni.navigateBack()
										},1500) 
									}
								})
							}
						}
					});
					}
				},
			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			// 删除图片
			deletePic(index) {
				this.fileList.splice(index, 1)
				this.saleOrderAttaches.splice(index,1)
				console.log(this.saleOrderAttaches,'this.saleOrderAttaches');
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			
			removeSuccess(index){
				// 组件删除成功后，需要处理接收的数组
				this.saleOrderAttaches.splice(index,1)
				console.log(this.saleOrderAttaches,'saleOrderAttaches');
			},
			uploadSuccess(data, index, lists, name){
				console.log('list :>> ', list);
			},
			onChooseComplete(lists, name) {
				console.log('lists :>> ', lists);
				const app = this;
				const config = this.vuex_config;
				const upload = (list,index)=>{
					uni.uploadFile({
					url: config.baseUrl + '/common/upload',
					filePath: list[index].url,
					name: 'file',
					header: {
						"Authorization":'Bearer ' + this.vuex_token
					},
					//	这个res是后端返回给你上传成功的数据里边一般会有上传之后图片的在线路径
					success: (res) => {
						let result = JSON.parse(res.data)
						if (result.code == 200) {
							this.$u.toast('上传成功');
							this.saleOrderAttaches.push({
								orderId:this.queryParam.id,
								attachPath:result.url.replace(/\\/g,'/')
								// attachType:1
							})
							this.$refs.upload_file.lists[index].progress = 100
						} else {
							this.$u.toast(result.msg);
						}
					},
				})
				}
				lists.forEach((val,index)=>{
					if(val.progress == 0){
						upload(lists,index)
					}
				})
			},
			
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			
			linkOrder(){
				this.navTo('/pages/sys/workbench/saleOrderList')
			},
			getAllUserList(){
				this.$u.api.bizUserAllList({}).then(res=>{
					if(res.code == 200){
						this.userList = res.data
					}
				})
			},
			
				// 注意返回值为一个数组，单列时取数组的第一个元素即可(只有一个元素)
				confirm(e) {
					this.$set(this.queryParam,'measurer',e[0].value+'')
					this.$set(this.queryParam,'measurerName',e[0].label+'')
				},
			
	
		}
		
	}
</script>

<style lang="scss" scoped>
@import 'index.scss';
page {
	background-color: #f5f5f5;
}
.wrap .search{
	background: #ffffff;
}
.apply-text{
	font-size: 28rpx;
	color: #333333;
	span{
		color: #999999;
	}
}
.user-images{
	width: 28px;
	height:28px;
	margin-right: 8px;
}
.apply-list-foot{
	font-size: 28rpx;
}
.personnel-list{
	display: flex;
	align-items: center;
	flex-wrap:wrap;
	.personnel-user{
		position: relative;
		margin: 5px 9px 0;
	}
	.user-images{
		width: 48px;
		height:48px;
		margin-right:0;
		
	}
	.iconfont{
		position: absolute;
		top:-12px;
		right:-5px;
		color: #FE0100;
	}
}
</style>